package com.wrt.wm.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;

/**
 * 重绘图片
 * 
 * @author 文瑞涛
 * @date 2020-7-27 16:32:01
 */
@Component
@Log4j2
public class RewriteImageUtil {

	@Value("${temppath.temp:temp}")
	private String temp;
	
	/**
	 * 
	 * 处理图片重绘
	 * 
	 * @param suffix 图片后缀名
	 * @param imgFile 图片文件对象
	 * @param img 图像缓冲器
	 * 
	 * @return 重绘后的图片地址
	 *
	 */
	public String handle(String suffix, File imgFile, BufferedImage img) {
		String path = temp;
		File temp = new File(path);
		if (!temp.exists()) {
			temp.mkdir();
		}
		String fileBaseName = FilenameUtils.getBaseName(imgFile.getName());
		switch (suffix) {
		case "jfif":
			path = path + File.separator + fileBaseName + ".jpg";
			jfif(img, path);
			break;
		case "tiff","tif":
			path = path + File.separator + fileBaseName + ".png";
			tiff(imgFile, path);
			break;
		default:
			path = path + File.separator + fileBaseName + "." + suffix;
			normal(img, path);
			break;
		}
		return path;
	}

	/**
	 * 
	 * 普通图像处理
	 * 
	 * @param img 图像缓冲器
	 * @param path 图片地址
	 *
	 */
	private void normal(BufferedImage img, String path) {
		try {
			Thumbnails.of(img).scale(1.0).toFile(path);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 
	 * jfif图像处理
	 * 
	 * @param img 图像缓冲器
	 * @param path 图片地址
	 *
	 */
	private void jfif(BufferedImage img, String path) {
		try {
			Thumbnails.of(img).scale(1.0).outputFormat("jpg").toFile(path);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 生成tiff原始dpi的png
	 * 
	 * @param tifFile 原始tif文件
	 * @param path    目标png
	 */
	private void tiff(File tifFile, String path) {
		try {
			BufferedImage tempImage = ImageIO.read(tifFile);
			ImageIO.write(tempImage, "png", new File(path));
		} catch (IOException e) {
			log.error("tif文件转换异常", e);
		}
	}
	
}
